/**
 * 
 */
package de.oszimtcc.timetablescreens;

import java.util.Date;

import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.TextView;
import de.oszimtcc.framework.BaseActivity;
import de.oszimtcc.framework.BaseScreen;
import de.oszimtcc.framework.Logger;
import de.oszimtcc.timetable.R;
import de.oszimtcc.timetable.TimetableApplication;
import de.oszimtcc.timetableadapter.DayAdapter;
import de.oszimtcc.timetablecore.Timetable;
import de.oszimtcc.timetablehelper.ApiWebservice;
import de.oszimtcc.timetablehelper.RequestCache;
import de.oszimtcc.timetableview.BlockListView;
import de.oszimtcc.timetableview.TimetableFlipperView;


/**
 * @author Kooki
 *
 */
public class TimetableScreen extends BaseScreen implements SensorEventListener
{
    TimetableFlipperView flipper;
    public Timetable actualTimetable;  
  
	SensorManager manager;
	float[] acceleration = new float[3];
	private static final long UPDATE_INTERVAL_THRESHOLD = 1;
	protected long lastupdate = 0;
    
    boolean change;
    
    public TimetableScreen(BaseActivity pBaseActivity,Timetable pTimetable)
    {
		super(pBaseActivity);
		Setup(R.layout.daily);
		Logger.Debug("Start create Timetable-Aplication");
         
        activity.inflater = LayoutInflater.from(this.activity);     
        
        flipper = (TimetableFlipperView)activity.findViewById(R.id.flipper); 
        
        actualTimetable = pTimetable;
        UpdateUI();
    }
    
	public TimetableScreen(BaseActivity pBaseActivity)
	{
		super(pBaseActivity);
		Setup(R.layout.daily);
		Logger.Debug("Start create Timetable-Aplication"); 
         
        activity.inflater = LayoutInflater.from(this.activity);  
        
        flipper = (TimetableFlipperView)activity.findViewById(R.id.flipper); 
        
		if(RequestCache.getInstance(activity.GetStringPreference("Class")).IsRequestNeeded())
		{
			Logger.Debug("Start showing waitdlg");
			StartWaitDialog();
			ApiWebservice.StartAsynchRequest(new Handler() 
				{
					@Override
					public void handleMessage(Message msg) 
					{
						if(msg.obj instanceof Timetable)
						{
							Logger.Debug("Got timetable from Request");
					        actualTimetable = (Timetable)msg.obj;
					        UpdateUI();
					        RequestCache.getInstance(activity.GetStringPreference("Class")).AddTimetable(actualTimetable);
					        RemoveWaitDialog();
						}
						if(msg.what == -1)
						{
							Logger.Error("Unable to got a valid Timetable");
							DrawError("Der Webserver wurde nicht erreicht.");
						}
						if(msg.what == -2)
						{
							Logger.Error("Unable to got a valid Timetable");
							DrawError("Der Stundenplan konnte nicht gelesen werden.");
						}
					}
				}); 
		}
		else
		{
			Logger.Debug("Need no update, request Timetable from database");
			actualTimetable = TimetableApplication.getInstance().getActualTimetable();
			if(actualTimetable == null)
			{
				DrawError("Der Stundenplan konnte nicht gelesen werden.");
			}
			else
				UpdateUI();
			//manager = (SensorManager)activity.getSystemService(Context.SENSOR_SERVICE);					
			//manager.registerListener(TimetableScreen.this, manager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_GAME );				
		}
    }
   
	public void UpdateUI()
	{
		switch(activity.getWindowManager().getDefaultDisplay().getRotation())
		{
			case 0:
			case 2:
				UpdateForPortrait();
				break;
			case 1:
			case 3:
				UpdateForLandscape();
				break;
			default:
				UpdateForPortrait();
				break;
		}
	}
	
	public void UpdateForPortrait()
	{       
    	for(int i = 0; i < ((ViewGroup)this.activity.findViewById(R.id.daily_showactualdayLayout)).getChildCount(); i++)
    	{
    		TextView dayText = (TextView)((ViewGroup)this.activity.findViewById(R.id.daily_showactualdayLayout)).getChildAt(i);
    		dayText.setOnClickListener(onActualShownDayClick);
    	}
    	
    	flipper.AddContent(actualTimetable);
		ShowActualDay();
	}
	
	public void UpdateForLandscape()
	{
		int rotation = activity.getWindowManager().getDefaultDisplay().getRotation();
    	if(rotation  == 1 || rotation == 3)
    	{
    		BlockListView[] week = new BlockListView[5];
    		week[0] = (BlockListView) activity.findViewById(R.id.dayListViewMonday);
    		week[1] = (BlockListView) activity.findViewById(R.id.dayListViewTuesday);
    		week[2] = (BlockListView) activity.findViewById(R.id.dayListViewWednesday);
    		week[3] = (BlockListView) activity.findViewById(R.id.dayListViewThursday);
    		week[4] = (BlockListView) activity.findViewById(R.id.dayListViewFriday);
    		
        	for (int i = 0; i < actualTimetable.getDayList().size(); i++)
        	{     		
    			DayAdapter dayListAdapter = new DayAdapter(this.activity, i, actualTimetable.getDayList().get(i).BlockList);
    			week[i].setAdapter(dayListAdapter);
        	}
    	}
	}
    
    public void UpdateDayBar() 
    {
    	TimetableApplication.getInstance().getActivity().SetStringPreference("flipperInitPosition", ""+flipper.getDisplayedChild());
    	for(int i = 0; i < ((ViewGroup)this.activity.findViewById(R.id.daily_showactualdayLayout)).getChildCount(); i++)
    	{
    		TextView dayText = (TextView) ((ViewGroup)this.activity.findViewById(R.id.daily_showactualdayLayout)).getChildAt(i);
    		if(flipper.getDisplayedChild() == i)
    		{
    			dayText.setTextAppearance(activity, R.style.ActualShownDay);
    		}
    		else
    			dayText.setTextAppearance(activity, R.style.ActualNotShownDay);
		}
    }
    
    private android.view.View.OnClickListener onActualShownDayClick = new android.view.View.OnClickListener()
	{		
		@Override
		public void onClick(View v)
		{
			flipper.setDisplayedChild(Integer.parseInt((String)v.getTag()));
			UpdateDayBar();
		}
	};
    
    private void ShowActualDay()
    {	
    	flipper.setDisplayedChild(Integer.parseInt(activity.GetStringPreference("flipperInitPosition")));
    	UpdateDayBar(); 
    }

	@Override
    public void onAccuracyChanged(Sensor sensor, int accuracy)
    {
	    // TODO Auto-generated method stub
	    
    }

	@Override
    public void onSensorChanged(SensorEvent event)
    {
		System.arraycopy( event.values, 0, acceleration, 0, 3 );
		
		long now = event.timestamp / 1000000;
		Date diff = new Date(now - lastupdate);
		Logger.Error("" + diff.getSeconds() + "   " + now + "   " + lastupdate);
		if(getAccelerationOnXAxis() > 4 && diff.getSeconds() > UPDATE_INTERVAL_THRESHOLD)
		{
			flipper.showNext();
			lastupdate = now;
		}
		if(getAccelerationOnXAxis() < -4 && diff.getSeconds() > UPDATE_INTERVAL_THRESHOLD)
		{
			flipper.showPrevious();
			lastupdate = now;
		}
		
	    
    }
	
	public float getAccelerationOnXAxis( )
	{
		return acceleration[0];
	}

	public float getAccelerationOnYAxis( )
	{
		return acceleration[1];
	}

	public float getAccelerationOnZAxis( )
	{
		return acceleration[2];
	}	
}
